import threading
import time
from datetime import datetime, timedelta
import json
from dataclasses import dataclass, asdict
from utils.common_util import pre_menus
from rest_framework.decorators import action
# 数据库model
from rest_framework import viewsets, permissions, status, mixins, serializers
from user.models import User, UserGroup, UserAccountBind, Message as UserMessage
from company.models import Company
from system.models import Menus
from platefrom.models import SkusUser

# 响应错误代码
from user.error_msg import AccountHasBeenExistError, PasswordError
from system.models import PhoneCaptcha
from system.error_msg import SmsTimeOutError, SmsError
from server.secret import tencent_sms_time_out

from django.db.models import Q
from .serializers import UserRegisterSerializer, UserGroupSerializer, UserSerializer, \
    MyTokenObtainPairSerializer, UserAccountBindSerializer \
    , UserEmployeeSerializer, MessageSerializer,UpdateWebPasswordSerializer

# api响应
from utils.response_util import APIResponse, Response, VueAPIResponse

# 分页
from utils.pagination_util import PageNumberPaginationUtil

# token

from rest_framework_simplejwt.views import TokenObtainPairView

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from server.utils import check_group_id

from django.core.cache import cache

# app
from server.urls import client
from ez_android_automator.bilibili_task import BilibiliPhoneLoginTask, bilibili_file_pkg, BilibiliPublishVideoTask
from ez_android_automator.xhs_task import XhsPhoneLoginTask,XhsPublishVideoTask,xhs_file_pkg
from ez_android_automator.kuaishou_task import KuaishouPhoneLoginTask,KuaishouPublishVideoTask,kuaishou_file_pkg
from ez_android_automator.app_file import PullAccountTask, PushAccountTask
from ez_android_automator.weibo_task import WeiboPhoneLoginTask, WeiboPublishVideoTask, weibo_file_pkg
from ez_android_automator.toutiao_task import ToutiaoPhoneLoginTask, ToutiaoPublishVideoTask, toutiao_file_pkg
from ez_android_automator.douyinhuoshan_task import DouyinhuoshanPhoneLoginTask, DouyinhuoshanPublishVideoTask, \
    douyinhuoshan_file_pkg

@permission_classes((AllowAny,))
class UserRegisterView(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserRegisterSerializer

    # def list(self, request, *args, **kwargs):
    #     results = {}
    #     queryset = self.filter_queryset(self.get_queryset())
    #     # results['company_list'] = Company.objects.values('id', 'name')
    #     return VueAPIResponse(self, queryset, results, data='data')
    #
    def create(self, request, *args, **kwargs):
        form = request.data.get('origin', 'mobile')
        username = request.data.get('username')
        code = request.data.get('code')
        password = request.data.get('password')
        re_password = request.data.get('re_password')
        reg_type = request.data.get("reg_type", 0)

        try:
            if form == 'mobile':
                record = PhoneCaptcha.objects.get(phone=username, code=code)
                if int(time.time()) - int(record.send_time) > tencent_sms_time_out:
                    raise SmsTimeOutError

            # 检查两次密码是否一致
            if password != re_password:
                raise PasswordError("两次密码不一致")

            # 检查用户名是否已经存在
            if User.objects.filter(username=username).exists():
                raise AccountHasBeenExistError

            # 创建新用户对象
            user = User.objects.create(username=username)

            # 设置用户密码
            user.set_password(password)

            # 同时在角色表添加一条信息 0-普通用户，1-企业管理员 2-企业员工，3企业负责人
            if reg_type == 0:  # 个人用户
                user.group_id = 2
                user.type = 0

            elif reg_type == 1:  # 企业员工

                # 选择公司
                company_id = request.data.get("company", 0)
                if company_id == 0:
                    return Response({'status': 'error', 'message': '请选择公司'},
                                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)

                company = Company.objects.filter(id=company_id).first()
                user.group_id = 4
                user.company_id = company_id
                user.company_name = company.name
                user.type = 2

            elif reg_type == 2:  # 企业管理员

                # 添加公司
                company_name = request.data.get("company_name", 0)
                if company_name == 0:
                    raise serializers.ValidationError('请输入公司名称')

                exist = Company.objects.filter(name=request.data.get("company_name")).values()
                if len(exist) > 0:
                    return Response({'status': 'error', 'message': '公司已存在'},
                                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                else:
                    company = Company.objects.create(name=request.data.get("company_name"))

                user.company_id = company.id
                user.company_name = company.name
                user.group_id = 3
                user.type = 1
            else:
                user.group_id = 2  # 默认为普通用户
                user.type = 0  # 默认为普通用户

            # 保存
            user.save()
            return Response({'status': 'success'}, status=status.HTTP_201_CREATED)

        except PhoneCaptcha.DoesNotExist:
            raise SmsError("验证码错误")

        except PasswordError as e:
            raise PasswordError(str(e))

        except Exception as e:
            # 处理其他可能的异常
            return Response({'status': 'error', 'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserGroupView(viewsets.ModelViewSet):
    queryset = UserGroup.objects.all()
    serializer_class = UserGroupSerializer

    def list(self, request, *args, **kwargs):
        group_list = self.queryset.all().order_by('id')
        name = request.GET.get('name')
        if name:
            group_list = group_list.filter(
                Q(name__icontains=name))
        serializer = self.get_serializer(group_list, many=True)
        return APIResponse(results=serializer.data)


class UserListView(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    pagination_class = PageNumberPaginationUtil

    def list(self, request, *args, **kwargs):

        if check_group_id(self.request.user.group_id) == 'super_admin':
            user_list = self.filter_queryset(self.get_queryset())
        elif check_group_id(self.request.user.group_id) == 'company_admin':
            # 查公司用户
            user_list = self.filter_queryset(self.get_queryset().filter(company_id=self.request.user.company_id))
        elif check_group_id(self.request.user.group_id) == 'person':
            # 查个人
            user_list = self.filter_queryset(self.get_queryset().filter(id=self.request.user.id))

        elif check_group_id(self.request.user.group_id) == 'staff':
            user_list = self.filter_queryset(self.get_queryset().filter(company_id=self.request.user.company_id))

        # user_list = self.queryset.all().order_by('id')
        username = request.GET.get('name')
        is_auth = request.GET.get('is_auth')
        is_newuser = request.GET.get('is_newuser')
        type = request.GET.get('type')

        if username:
            user_list = user_list.filter(
                Q(username__icontains=username))
        if is_newuser:
            user_list = user_list.filter(
                Q(is_newuser=is_newuser))
        if type:
            user_list = user_list.filter(
                Q(type=type))
        if is_auth:
            user_list = user_list.filter(
                Q(is_auth=is_auth))

        page = self.paginate_queryset(user_list)
        serializer = self.get_serializer(user_list, many=True)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
        return APIResponse(results=self.get_paginated_response(serializer.data).data)

    @action(methods=['get'], detail=False, url_path='personal')
    def personal_list(self, request, *args, **kwargs):

        queryset = self.get_queryset().filter(type=0, is_auth=1)
        serializer = self.get_serializer(queryset, many=True)
        return APIResponse(results=serializer.data)

    @action(methods=['post'], detail=False, url_path='auth_user_with_company')
    def auth_user_with_company(self, request, *args, **kwargs):
        post_data = self.request.data

        # 更新用户数据
        user_data = {}
        user_data['mobile'] = post_data['mobile']
        user_data['id_card'] = post_data['id_card']
        user_data['id_card_back_image_id'] = post_data['id_card_back_image_id']
        user_data['id_card_back_url'] = post_data['id_card_back_url']
        user_data['id_card_front_image_id'] = post_data['id_card_front_image_id']
        user_data['id_card_front_url'] = post_data['id_card_front_url']
        user_data['nickname'] = post_data['nickname']
        user_data['first_name'] = post_data['first_name']
        user_data['is_auth'] = 3
        User.objects.filter(id=post_data['user_id']).update(**user_data)

        # 更新公司数据
        company_data = {}
        company_data['mobile'] = post_data['company_mobile']
        company_data['license_number'] = post_data['company_license_number']
        company_data['id_card'] = post_data['company_id_card']
        company_data['corporation_back_image_id'] = post_data['company_corporation_back_image_id']
        company_data['corporation_back_url'] = post_data['company_corporation_back_url']
        company_data['corporation_front_image_id'] = post_data['company_corporation_front_image_id']
        company_data['corporation_front_url'] = post_data['company_corporation_front_url']
        company_data['corporation'] = post_data['company_corporation']
        company_data['license_url'] = post_data['company_license_url']
        company_data['image_id'] = post_data['company_image_id']

        Company.objects.filter(id=post_data['company_id']).update(**company_data)
        return APIResponse(results={})

    @action(methods=['get'], detail=False, url_path='all')
    def all_list(self, request, *args, **kwargs):

        if check_group_id(self.request.user.group_id) == 'super_admin':
            queryset = self.get_queryset().exclude(group_id=1).filter()
        elif check_group_id(self.request.user.group_id) == 'company_admin':
            # 查公司用户
            queryset = self.get_queryset().filter(company_id=self.request.user.company_id)
        elif check_group_id(self.request.user.group_id) == 'person':
            # 查个人
            queryset = self.get_queryset().filter(id=self.request.user.id)

        elif check_group_id(self.request.user.group_id) == 'staff':
            queryset = self.get_queryset().filter(company_id=self.request.user.company_id)

        # 查询除了超级管理员外的所有用户
        # queryset = self.get_queryset().filter().exclude(group_id=1)
        serializer = self.get_serializer(queryset, many=True)
        return APIResponse(results=serializer.data)


class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer


task_instances = {}


class UserInfoView(viewsets.ModelViewSet):
    """获取用户信息"""
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def call(self, task):
        self.is_success = True

    def list(self, request, *args, **kwargs):

        user = self.request.user

        try:
            # 用户信息
            user = User.objects.get(pk=user.id)
            # 用户分组信息
            group = UserGroup.objects.filter(id=user.group_id).first()

            # 用户绑定套餐
            if user.type == '0':
                user_skus = SkusUser.objects.filter(user_id=user.id).first()
            else:
                user_skus = SkusUser.objects.filter(company_id=user.company_id).first()
            if user_skus:
                skus_id = user_skus.skus_id
                skus_title = user_skus.title
            else:
                skus_id = 1 # 基础套餐
                skus_title = '基础套餐'

            if len(group.rules) > 0:
                rules = group.rules.split(",")
                menus = Menus.objects.filter(id__in=rules, is_menu=1).values()
                menus = pre_menus(menus)
            else:
                menus = []
            results = {
                "menus": menus,
                'username': user.username,
                'nickname': user.nickname,
                'skus_id': skus_id,
                'skus_title': skus_title,
                'is_newuser': user.is_newuser,
                'type': user.type,
                'company_id': user.company_id,
                'company_name': user.company_name,
                'group': user.group_id,
                'id': user.id,
                'is_auth': user.is_auth,
                'first_name': user.first_name,
                'mobile': user.mobile,
                'id_card': user.id_card,
                'back_reason': user.back_reason,
                'id_card_back_url': user.id_card_back_url,
                'id_card_front_url': user.id_card_front_url,
            }
            return VueAPIResponse(self, results, data=results)
        except Exception as e:
            return Response({'status': 'error', 'message': str(e)}, status=400)

    @action(methods=['put'], detail=False, url_path='set_newuser')
    def set_newuser(self, request, *args, **kwargs):

        # 查询除了超级管理员外的所有用户
        updateData = self.request.data
        id = updateData['id']
        updateData.pop('id')
        User.objects.filter(id=id).update(**updateData)

        user = User.objects.get(pk=id)
        group = UserGroup.objects.filter(id=user.group_id).first()

        if len(group.rules) > 0:
            rules = group.rules.split(",")
            menus = Menus.objects.filter(id__in=rules, is_menu=1).values()
            menus = pre_menus(menus)
        else:
            menus = []

        # 用户绑定套餐
        if user.type == '0':
            user_skus = SkusUser.objects.filter(user_id=user.id).first()
        else:
            user_skus = SkusUser.objects.filter(company_id=user.company_id).first()
        if user_skus:
            skus_id = user_skus.skus_id
            skus_title = user_skus.title
        else:
            skus_id = 1  # 基础套餐
            skus_title = '基础套餐'

        results = {
            "menus": menus,
            'username': user.username,
            'nickname': user.nickname,
            'skus_id': skus_id,
            'skus_title': skus_title,
            'is_newuser': user.is_newuser,
            'type': user.type,
            'company_id': user.company_id,
            'company_name': user.company_name,
            'group': user.group_id,
            'id': user.id,
            'is_auth': user.is_auth,
            'first_name': user.first_name,
            'mobile': user.mobile,
            'id_card': user.id_card,
            'back_reason': user.back_reason,
            'id_card_back_url': user.id_card_back_url,
            'id_card_front_url': user.id_card_front_url,
        }
        return VueAPIResponse(self, results, data=results)

    @action(methods=['put'], detail=False, url_path='get_login_app_dir_phone')
    def get_login_app_dir_phone(self, request, *args, **kwargs):

        # 查询除了超级管理员外的所有用户
        data = self.request.data

        # 获取用户账户
        user_account = UserAccountBind.objects.filter(id=data['id']).first()

        # 登录操作
        if user_account.en_name == 'bilibili':
            task = BilibiliPhoneLoginTask(user_account.plate_account)
        if user_account.en_name == 'xiaohongshu':
            task = XhsPhoneLoginTask(user_account.plate_account)
        if user_account.en_name == 'kuaishou':
            task = KuaishouPhoneLoginTask(user_account.plate_account)
        if user_account.en_name == 'toutiao':
            task = ToutiaoPhoneLoginTask(user_account.plate_account)
        if user_account.en_name == 'douyinhuoshan':
            task = DouyinhuoshanPhoneLoginTask(user_account.plate_account)
        if user_account.en_name == 'weibo':
            task = WeiboPhoneLoginTask(user_account.plate_account)
        client.set_task(task)

        # 存储任务实例引用到全局字典
        task_instances[user_account.plate_account] = task
        cache.set(f'task_{user_account.plate_account}', user_account.plate_account, timeout=300)
        print(f'Task stored in cache for phone: {user_account.plate_account}')  # 打印存储的任务对象
        print(task)
        # 在后台运行任务
        threading.Thread(target=self.run_task, args=(task,)).start()

        return Response({'detail': '推送电话成功！', 'code': 200}, status=status.HTTP_200_OK)

    def run_task(self, phone):
        try:
            client.run_current_task()
            # 任务完成后不需要更新缓存，因为实例引用已经存储在全局字典中
            print(f'Task completed for phone: {phone}')
        except Exception as e:
            print(f'Task execution failed for phone {phone}: {e}')

    @action(methods=['put'], detail=False, url_path='push_login_app_dir_code')
    def push_login_app_dir_code(self, request, *args, **kwargs):

        # 查询除了超级管理员外的所有用户
        data = self.request.data

        # 获取用户账户
        user_account = UserAccountBind.objects.filter(id=data['id']).first()

        # 推送登录文件
        if user_account.en_name == 'bilibli':
            task2 = PushAccountTask(bilibili_file_pkg, f'media/app/',
                                    f'{user_account.plate_account}_{user_account.en_name}')
        if user_account.en_name == 'xiaohongshu':
            task2 = PushAccountTask(xhs_file_pkg, f'media/app/',
                                    f'{user_account.plate_account}_{user_account.en_name}')
        if user_account.en_name == 'kuaishou':
            task2 = PushAccountTask(kuaishou_file_pkg, f'media/app/',
                                    f'{user_account.plate_account}_{user_account.en_name}')
        if user_account.en_name == 'douyinhuoshan':
            task2 = PushAccountTask(douyinhuoshan_file_pkg, f'media/app/',
                                    f'{user_account.plate_account}_{user_account.en_name}')
        if user_account.en_name == 'weibo':
            task2 = PushAccountTask(weibo_file_pkg, f'media/app/',
                                    f'{user_account.plate_account}_{user_account.en_name}')
        if user_account.en_name == 'toutiao':
            task2 = PushAccountTask(toutiao_file_pkg, f'media/app/',
                                    f'{user_account.plate_account}_{user_account.en_name}')

        client.set_task(task2)  # 设置任务
        client.run_current_task()  # 开始运行任务

        return Response({'detail': '推送成功！', 'code': 200}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=False, url_path='get_login_app_dir_code')
    def get_login_app_dir_code(self, request, *args, **kwargs):

        # 查询除了超级管理员外的所有用户
        data = self.request.data

        # 获取用户账户
        user_account = UserAccountBind.objects.filter(id=data['id']).first()

        # 从缓存中获取任务的键
        cached_phone = cache.get(f'task_{user_account.plate_account}')
        if not cached_phone:
            return Response({'detail': '验证码任务尚未创建或未完成'}, status=status.HTTP_400_BAD_REQUEST)

        # 从全局字典中获取任务实例
        task = task_instances.get(cached_phone)
        if not task:
            return Response({'detail': '任务实例不存在或已过期'}, status=status.HTTP_400_BAD_REQUEST)

        print(f'Task retrieved from global dictionary for phone: {user_account.plate_account}')  # 打印检索到的任务对象

        # 发送验证码
        try:
            task.send_captcha(data['code'])
            self.call(task)
        except Exception as e:
            return Response({'detail': f'发送验证码失败: {e}'}, status=status.HTTP_400_BAD_REQUEST)
        # self.call([])
        if self.is_success:
            # 拉取app文件夹
            # task = PullAccountTask(bilibili_file_pkg, f'./media/app/', f'{user_account.plate_account}_{user_account.en_name}')
            # client.set_task(task)  # 设置任务
            # client.run_current_task()  # 开始运行任务
            #
            # UserAccountBind.objects.filter(id=data['id']).update(app_account_upload=f'media/app/{user_account.plate_account}_{user_account.en_name}')

            return Response({'detail': '绑定成功', 'code': 1}, status=status.HTTP_200_OK)
        else:
            return Response({'detail': '绑定失败', 'code': 2}, status=status.HTTP_400_BAD_REQUEST)

    @action(methods=['get'], detail=False, url_path='get_app_login_file')
    def get_app_login_file(self, request, *args, **kwargs):

        # 查看用户角色
        user_group_id = self.request.user.group_id
        if check_group_id(user_group_id) == 'person':
            user_id = self.request.user.id
            user_account = UserAccountBind.objects.filter(Q(user_id=user_id)).exclude(app_account_upload='').values()
            # 获取公司的套餐
        elif check_group_id(user_group_id) == 'staff' or check_group_id(
                user_group_id) == 'company_admin':
            company_id = self.request.user.company_id
            user_account = UserAccountBind.objects.filter(Q(company_id=company_id)).exclude(app_account_upload='').values()
        else:
            user_account = []
        return APIResponse(results=user_account)

    @action(methods=['put'], detail=False, url_path='get_app_file')
    def get_app_file(self, request, *args, **kwargs):

        # 查询除了超级管理员外的所有用户
        data = self.request.data

        # 获取用户账户
        user_account = UserAccountBind.objects.filter(id=data['id']).first()

        # 发送验证码
        try:
            # 拉取app文件夹

            if user_account.en_name == 'bilibili':
                task = PullAccountTask(bilibili_file_pkg, f'./media/app/',
                                   f'{user_account.plate_account}_{user_account.en_name}')
            if user_account.en_name == 'toutiao':
                task = PullAccountTask(toutiao_file_pkg, f'./media/app/',
                                       f'{user_account.plate_account}_{user_account.en_name}')
            if user_account.en_name == 'weibo':
                task = PullAccountTask(weibo_file_pkg, f'./media/app/',
                                       f'{user_account.plate_account}_{user_account.en_name}')
            if user_account.en_name == 'xiaohongshu':
                task = PullAccountTask(xhs_file_pkg, f'./media/app/',
                                       f'{user_account.plate_account}_{user_account.en_name}')
            if user_account.en_name == 'douyinhuoshan':
                task = PullAccountTask(douyinhuoshan_file_pkg, f'./media/app/',
                                       f'{user_account.plate_account}_{user_account.en_name}')
            if user_account.en_name == 'kuaishou':
                task = PullAccountTask(kuaishou_file_pkg, f'./media/app/',
                                       f'{user_account.plate_account}_{user_account.en_name}')

            client.set_task(task)  # 设置任务
            client.run_current_task()  # 开始运行任务

            UserAccountBind.objects.filter(id=data['id']).update(
                app_account_upload=f'media/app/{user_account.plate_account}_{user_account.en_name}')
            return Response({'detail': '拉取成功', 'code': 200}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'detail': f'拉取账户失败: {e}'}, status=status.HTTP_400_BAD_REQUEST)


class UserAccountBindViewSets(viewsets.ModelViewSet):
    """平台账号绑定"""
    queryset = UserAccountBind.objects.all()
    pagination_class = PageNumberPaginationUtil
    serializer_class = UserAccountBindSerializer

    def list(self, request, *args, **kwargs):
        if check_group_id(self.request.user.group_id) == 'super_admin':
            list = self.queryset.filter().order_by('id')
        elif check_group_id(self.request.user.group_id) == 'company_admin':
            # 查公司用户
            list = self.queryset.filter(company_id=self.request.user.company_id).order_by('id')
        elif check_group_id(self.request.user.group_id) == 'person':
            # 查个人
            list = self.queryset.filter(user_id=self.request.user.id).order_by('id')

        elif check_group_id(self.request.user.group_id) == 'staff':
            list = self.queryset.filter(company_id=self.request.user.company_id).order_by('id')

        # list = self.queryset.all().order_by('id')
        name = request.GET.get('name')
        type = request.GET.get('type')
        if name:
            list = list.filter(
                Q(username__icontains=name) | Q(company_name__icontains=name))
        if type:
            list = list.filter(
                Q(type=type))
        page = self.paginate_queryset(list)
        serializer = self.get_serializer(list, many=True)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
        return APIResponse(results=self.get_paginated_response(serializer.data).data)


# 员工-视图
class UserEmployeeView(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserEmployeeSerializer

    def list(self, request, *args, **kwargs):
        company_id = self.request.user.company_id

        if company_id:
            user_list = self.queryset.filter(company_id=company_id).order_by('id')
        else:
            user_list = self.queryset.filter(company_id__isnull=False).order_by('id')

        name = request.GET.get('search')
        if name:
            user_list = user_list.filter(
                Q(username__icontains=name) | Q(company_name__icontains=name))


        page = self.paginate_queryset(user_list)
        serializer = self.get_serializer(user_list, many=True)
        if page is not None:
            serializer = self.get_serializer(user_list, many=True)
        return APIResponse(results=self.get_paginated_response(serializer.data).data)

    @action(methods=['post'], detail=False, url_path='set_employee')
    def all_list(self, request, *args, **kwargs):
        # 查询普通用户
        req_data = self.request.data

        if not req_data['department_id'] or not req_data['selectEmployeeValue']:
            raise serializers.ValidationError('请选择部门或者员工！')

        User.objects.filter(id__in=req_data['selectEmployeeValue']).update(department_id=req_data['department_id'])
        return APIResponse()


class MessageViewSet(viewsets.ModelViewSet):
    """公司消息"""
    queryset = UserMessage.objects.filter()
    serializer_class = MessageSerializer
    search_fields = ['content', 'title']
    pagination_class = PageNumberPaginationUtil

    def list(self, request, *args, **kwargs):
        if check_group_id(self.request.user.group_id) == 'super_admin':
            queryset = self.filter_queryset(self.get_queryset())
        elif check_group_id(self.request.user.group_id) == 'company_admin':
            # 查公司部门
            queryset = self.filter_queryset(self.get_queryset().filter(company_id=self.request.user.company_id))
        elif check_group_id(self.request.user.group_id) == 'staff':
            queryset = self.filter_queryset(self.get_queryset().filter(user_id=self.request.user.id))

        title = request.GET.get('title')
        is_read = request.GET.get('is_read')
        if title:
            queryset = queryset.filter(
                Q(title__icontains=title))

        if is_read:
            queryset = queryset.filter(
                Q(is_read=is_read))

        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(queryset, many=True)
        if page is not None:
            serializer = self.get_serializer(queryset, many=True)
        return APIResponse(results=self.get_paginated_response(serializer.data).data)

    @action(methods=['post'], detail=False, url_path='set_read')
    def all_list(self, request, *args, **kwargs):
        # 查询普通用户
        req_data = self.request.data

        if not req_data['id']:
            raise serializers.ValidationError('数据错误！')

        UserMessage.objects.filter(id=req_data['id']).update(is_read=1)
        return APIResponse()

class UpdateWebPasswordViewSet(viewsets.ModelViewSet):
    """修改密码"""
    queryset = User.objects.all()
    serializer_class = UpdateWebPasswordSerializer

    def get_queryset(self):
        """只能访问本人数据"""
        return super().get_queryset().filter(pk=self.request.user.pk)

    def update(self, request, *args, **kwargs):
        # 创建新用户对象
        user = User.objects.filter(id=request.user.id).first()

        # 设置用户密码
        user.set_password(request.data['password'])
        user.save()
        return APIResponse()